package com.cxy.instarsystem.service;

import com.cxy.instarsystem.dao.SerialNoRepository;
import com.cxy.instarsystem.po.SerialNo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class SerialNoServiceImpl implements SerialNoService{
    @Autowired
    private SerialNoRepository serialNoRepository;
    private final char[] dics = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    //生成一个
    private String generateSerialNo(){
        Random rd = new Random();
        StringBuilder code= new StringBuilder();
        for (int k = 0; k < 6; k++) {
            int index = rd.nextInt(this.dics.length);
            code.append(dics[index]);
        }
        return code.toString();
    }

    @Override
    //是否重复
    public String getSerialNo() {
        String serialNoStr = this.generateSerialNo();
        SerialNo queryRequest = new SerialNo();
        queryRequest.setSerialNo(serialNoStr);
        while(serialNoRepository.exists(Example.of(queryRequest))){
            serialNoStr = this.generateSerialNo();
        }
        return serialNoStr;
    }


    @Override
    public boolean checkSerialNo(String serialNoStr, String certification) {
        SerialNo queryRequest = new SerialNo();
        queryRequest.setSerialNo(serialNoStr);
        return serialNoRepository.findOne(Example.of(queryRequest)).map(queryResult->{
            if(queryResult.getIsValid()==0 || queryResult.getIsUsed()==1){
                return false;
            }
            queryResult.setBindCertification(certification);
            queryResult.setIsUsed(1);
            serialNoRepository.save(queryResult);
            return true;
        }).orElse(false);
    }
}